package com.sx.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.sx.core.utils.JwtUtils;
import com.sx.core.utils.Md5;
import com.sx.core.utils.PropertyUtils;
import com.sx.wechat.security.Principal;
import com.sx.wechat.security.SimpleOAuthAuthzRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *获取一卡通授权信息
 *
 * @author <a href="mailto:lihao@ozstrategy.com">Hao Li</a>
 * @version 01/13/2018 11:15
 */
@RestController
public class UserAuthorizeController {
    //~ Instance fields --------------------------------------------------------------------------------------------------

    protected final transient Log logger = LogFactory.getLog(getClass());

    private String auth_username=PropertyUtils.getProperty("api.token.username");
    private String auth_password=PropertyUtils.getProperty("api.token.password");
    private String auth_client_id=PropertyUtils.getProperty("api.token.client_id");
    private String auth_client_secret=PropertyUtils.getProperty("api.token.client_secret");

    //~ Methods ----------------------------------------------------------------------------------------------------------
    @RequestMapping(value = "/information_authorize")
    public HttpEntity client_authorize(Model model, HttpServletRequest request, HttpServletResponse httpServletResponse) throws OAuthSystemException {
        try {
            // 构建OAuth 授权请求
            SimpleOAuthAuthzRequest oauthRequest = new SimpleOAuthAuthzRequest(request);
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //检查用户名密码
            if(!StringUtils.equals(auth_username,username)){
                logger.error("户名密码错误");
                return ResponseEntity.badRequest().build();
            }
            if(!StringUtils.equalsIgnoreCase(Md5.md5(password),auth_password)){
                logger.error("户名密码错误");
                return ResponseEntity.badRequest().build();
            }

            // 检查传入的客户端id是否正确
            if (!StringUtils.equals(auth_client_id,oauthRequest.getClientId())) {
                logger.error("客户端不匹配");
                return ResponseEntity.badRequest().build();
            }
            // 检查客户端安全KEY是否正确
            if (!StringUtils.equals(oauthRequest.getClientSecret(),auth_client_secret)) {
                logger.error("户端安全KEY不匹配");
                return ResponseEntity.badRequest().build();
            }
            String operCode=request.getParameter("operCode");
            String no=request.getParameter("no");
            if(StringUtils.isEmpty(no) || StringUtils.isEmpty(operCode)){
                return ResponseEntity.badRequest().build();
            }
            // 生成token
            String authorizationToken = null;
            // responseType目前仅支持CODE，另外还有TOKEN
            String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
            if (responseType.equals(ResponseType.TOKEN.toString())) {
                OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
                authorizationToken = "one-user-"+oauthIssuerImpl.accessToken();
                //保存token
                Principal principal=new Principal();
                principal.setBindno(no);
                principal.setBindtype(operCode);

                String sub_ject= JSON.toJSONString(principal);
                String token= JwtUtils.createJWT(authorizationToken,sub_ject);
                // 生成OAuth响应
                OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(
                        token).setExpiresIn("1800000").buildJSONMessage();
                // 根据OAuthResponse生成ResponseEntity
                return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
            }
        } catch (OAuthProblemException e) {
            logger.error("get token error with clientId>>>",e);
            return ResponseEntity.badRequest().build();
        }catch (Exception ex){
            logger.error("get token error with clientId>>>",ex);
        }
        return ResponseEntity.badRequest().build();
    } // end method authorize
} // end class AuthorizeController
